/*
Copyright SecureKey Technologies Inc. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package invoke

import (
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/common/verifier"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/ichain"

	"github.com/pkg/errors"
)

func NewSignatureValidationHandler(next ...Handler) *SignatureValidationHandler {
	return &SignatureValidationHandler{next: getNext(next)}
}

type SignatureValidationHandler struct {
	next Handler
}

func (f *SignatureValidationHandler) Handle(requestContext *RequestContext, clientContext *ClientContext) {
	err := f.validate(requestContext.Response.Responses, clientContext)
	if err != nil {
		requestContext.Error = errors.WithMessage(err, "signature validation failed")
		return
	}

	if f.next != nil {
		f.next.Handle(requestContext, clientContext)
	}
}

func (f *SignatureValidationHandler) validate(txProposalResponse []*ichain.TransactionProposalResponse, ctx *ClientContext) error {
	for _, r := range txProposalResponse {
		if err := verifyProposalResponse(r, ctx); err != nil {
			return err
		}
	}

	return nil
}

func verifyProposalResponse(res *ichain.TransactionProposalResponse, ctx *ClientContext) error {
	sv := &verifier.Signature{Membership: ctx.Membership}
	return sv.Verify(res)
}
